package com.aabte.springcloudlearn.common.constants;

import com.aabte.springcloudlearn.common.annotations.HttpCode;
import org.springframework.http.HttpStatus;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Daniel
 */
public interface ErrorConstants {

    /**
     * 0 - 1000 http
     */
    @HttpCode(httpStatus = HttpStatus.OK, message = "OK")
    String SUCCESS = HttpStatus.OK.toString();

    @HttpCode(httpStatus = HttpStatus.INTERNAL_SERVER_ERROR, message = "Internal Server Error")
    String INTERNAL_SERVER_ERROR = HttpStatus.INTERNAL_SERVER_ERROR.toString();


    /**
     * 1000 - 1999 公用
     */
    @HttpCode(httpStatus = HttpStatus.BAD_REQUEST, message = "Parameter is incorrect.")
    String PARAMETER_IS_INCORRECT = "1000";


    // =========================================================================


    Map<String, HttpCode> CODE_HTTP_CODE_MAP = new HashMap<>(ErrorConstants.class.getFields().length);

    static Map<String, HttpCode> getCodeHttpCodeMap() {
        if (!CODE_HTTP_CODE_MAP.isEmpty()) {
            return CODE_HTTP_CODE_MAP;
        }
        Field[] fields = ErrorConstants.class.getFields();
        for (Field field: fields) {
            boolean isFinal = Modifier.isFinal(field.getModifiers());
            if(isFinal){
                try {
                    Object rs = field.get(null);
                    if (rs instanceof String) {
                        HttpCode httpCode = field.getDeclaredAnnotation(HttpCode.class);
                        CODE_HTTP_CODE_MAP.put((String) rs, httpCode);
                    }
                } catch (IllegalAccessException e) {
                    // nothing
                }
            }
        }
        return CODE_HTTP_CODE_MAP;
    }

}
